﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using System.ComponentModel;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Input;
using 充电桩上位机.Model.PEM;
using 充电桩上位机.Model.PTAConfig;
using 充电桩上位机.Model.ServerRegisters;
using 充电桩上位机.ViewModel.SerialPortConnection;

namespace 充电桩上位机.ViewModel.MarkBook;

public class MarkBookViewModel : ObservableObject
{
    [Category("证书读取按钮内容")]
    private string _downLoadBookByRegisiter = string.Empty;
    public string DownLoadBookByRegisiter
    {
        get => _downLoadBookByRegisiter;
        set => SetProperty(ref _downLoadBookByRegisiter, value);
    }
    [Category("证书读取按钮内容")]
    private string _downLoadBookByFile = string.Empty;
    public string DownLoadBookByFile
    {
        get => _downLoadBookByFile;
        set => SetProperty(ref _downLoadBookByFile, value);
    }

    [Category("证书读取按钮内容")]
    private bool _processIsRun = false;
    public bool ProcessIsRun
    {
        get => _processIsRun;
        set => SetProperty(ref _processIsRun, value);
    }
    public ICommand DownLoadBookByFileCommand =>
    new RelayCommand(async () => await DownLoadBookByFileCommandFunc());
    private X509Certificate2 baselearndata { get; set; }
    private string readfilename { get; set; } = string.Empty;
    private string pemContent { get; set; } = string.Empty;
    public async Task DownLoadBookByFileCommandFunc()
    {
        OpenFileDialog openFileDialog = new()
        {
            Filter = "pem file|*.pem",
            DefaultExt = ".pem"
        };
        if (openFileDialog.ShowDialog() == true)
        {
            ProcessIsRun = true;
            //clear 并进行填充
            await Task.Delay(500);
            await System.Windows.Application.Current.Dispatcher.InvokeAsync(async delegate
            {
                PEMModel pEMModel = new();

                //Console.WriteLine("证书主题: " + certificate.Subject);
                //Console.WriteLine("证书发行者: " + certificate.Issuer);
                //Console.WriteLine("证书有效期开始: " + certificate.NotBefore);
                //Console.WriteLine("证书有效期结束: " + certificate.NotAfter);
                //Console.WriteLine("证书序列号: " + certificate.SerialNumber);
                pemContent = System.IO.File.ReadAllText(openFileDialog.FileName);
                baselearndata = await pEMModel.PEMModelReget(pemContent);


                readfilename = openFileDialog.FileName;
                MainWindowViewModel.pTAConfigModel.服务器证书字符串 = string.Empty;
                MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书主题: " + baselearndata.Subject + "\r\n";
                MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书发行者: " + baselearndata.Issuer + "\r\n";
                MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书有效期开始: " + baselearndata.NotBefore + "\r\n";
                MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书有效期结束: " + baselearndata.NotAfter + "\r\n";
                MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书序列号: " + baselearndata.SerialNumber + "\r\n";

                PageLikeText = MainWindowViewModel.pTAConfigModel.服务器证书字符串;
                ProcessIsRun = false;
            });
            //打开该文件并将内容加载进PTA

        }
    }
    public ICommand DownLoadBookByRegCommand =>
    new RelayCommand(async () => await DownLoadBookByRegCommandFunc());
    public async Task DownLoadBookByRegCommandFunc()
    {
        if (!SerialPortConnectionViewModel._joinCommand)
        {
            var uiMessageBox = new Wpf.Ui.Controls.MessageBox
            {
                Title = "Error",
                Content = "Please Open Serial Port First.",
            };
            var result = uiMessageBox.ShowDialogAsync();
            return;
        }
        ProcessIsRun = true;
        //clear 并进行填充
        await Task.Delay(500);
        string cakedata = string.Empty;
        for (int i = 0; i < 15; i++)
        {
            var page = await SerialPortConnectionViewModel.iAQBHController.AQReadData(MainWindowViewModel.theslaveaddr,
                (ushort)(mB_ServerRegisiters.服务器CA证书内容 + 100 * i), 100);

            cakedata += MainWindowViewModel.UShortToString(page, 0, 100, 200, true);

            await MainWindowViewModel.ChangeTheProcess((int)(mB_ServerRegisiters.服务器CA证书文件名 + 100 * i), (int)(mB_ServerRegisiters.服务器CA证书文件名 + 1500));
        }

        if (!string.IsNullOrEmpty(cakedata))
        {
            //byte[] publicKeyBytes = Convert.FromBase64String(cakedata);
            // 使用X509Certificate2类加载证书
            PEMModel pEMModel = new();
            string publicKeyBase64 = cakedata
                .Replace("-----BEGIN CERTIFICATE-----", "")
                .Replace("-----END CERTIFICATE-----", "")
                .Replace("\n", "")
                .Replace("\r", "");

            byte[] expectedBytes = Encoding.Default.GetBytes(publicKeyBase64);
            string base64String = Convert.ToBase64String(expectedBytes);
            baselearndata = await pEMModel.PEMModelReget(base64String);
            MainWindowViewModel.pTAConfigModel.服务器证书字符串 = string.Empty;
            MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书主题: " + baselearndata.Subject + "\r\n";
            MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书发行者: " + baselearndata.Issuer + "\r\n";
            MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书有效期开始: " + baselearndata.NotBefore + "\r\n";
            MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书有效期结束: " + baselearndata.NotAfter + "\r\n";
            MainWindowViewModel.pTAConfigModel.服务器证书字符串 += "证书序列号: " + baselearndata.SerialNumber + "\r\n";
        }

        PageLikeText = MainWindowViewModel.pTAConfigModel.服务器证书字符串!;
        ProcessIsRun = false;
    }   
    [Category("证书显示内容")]
    private string _pageLikeText = string.Empty;
    public string PageLikeText
    {
        get => _pageLikeText;
        set => SetProperty(ref _pageLikeText, value);
    }

    [Category("下载按钮")]
    private string _downloadFileText = string.Empty;
    public string DownloadFileText
    {
        get => _downloadFileText;
        set => SetProperty(ref _downloadFileText, value);
    }

    public ICommand DownloadFileCommand => new RelayCommand(async () => await DownloadFileCommandFunc());
    public async Task DownloadFileCommandFunc()
    {
        if (!SerialPortConnectionViewModel._joinCommand)
        {
            var uiMessageBox = new Wpf.Ui.Controls.MessageBox
            {
                Title = "Error",
                Content = "Please Open Serial Port First.",
            };
            var result = uiMessageBox.ShowDialogAsync();
            return;
        }

        List<MainWindowViewModel.HelpWithRegFunction> helpWithRegFunction = new();
        ProcessIsRun = true;
        await Task.Delay(500);
        if (!string.IsNullOrEmpty(baselearndata.ToString(true)))
        {
            string data = System.IO.File.ReadAllText(readfilename);
            // 去掉PEM文件中的头部和尾部，保留Base64内容
            //string data = baselearndata.ToString(true);
            var ushortdata = MainWindowViewModel.StrignToUShort(data, 1500, false);


            for (int i = 0; i < 15; i++)
            {
                helpWithRegFunction.Add(new MainWindowViewModel.HelpWithRegFunction
                {
                    data = ushortdata.Skip(i * 100).Take(100).ToArray(),
                    regaddr = (ushort)(mB_ServerRegisiters.服务器CA证书内容 + 100 * i)
                });
            }
        }
        foreach (var help in helpWithRegFunction)
        {
            int index = helpWithRegFunction.IndexOf(help);
            //如果我的slave id 变更了，我该如何得治
            await SerialPortConnectionViewModel.
                iAQBHController.AQBHSendData((MainWindowViewModel.theslaveaddr), help.regaddr, help.data);
            //搞一个进度条转圈
        }
        ProcessIsRun = false;
    }
    public MarkBookViewModel()
    {
        //PageLikeText = MainWindowViewModel.pTAConfigModel.服务器证书字符串!;
        DownLoadBookByFile = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "DownLoad Book By File");
        DownLoadBookByRegisiter = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "DownLoad Book By Regisiter");
        DownloadFileText = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "Download File");
    }
}
